package com.cqcet.wenchuang.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqcet.wenchuang.common.R;
import com.cqcet.wenchuang.common.customException.CustomException;
import com.cqcet.wenchuang.entity.User;
import com.cqcet.wenchuang.service.LoginService;
import com.cqcet.wenchuang.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Api(tags = "用户账号管理接口")
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录功能，登录成功将用户id存放入session中
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R<User> login(@RequestBody User user) {
        return userService.login(user);
    }

    public R<User> login(@RequestBody User user, HttpServletRequest request) {
        //添加查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //用户名唯一，按照用户名查询
        queryWrapper.eq(User::getUsername, user.getUsername());
        User u = userService.getOne(queryWrapper);
        //如果没有查询到返回登录失败结果
        if (Objects.isNull(u)) {
            return R.error("用户名不存在");
        }
        //比对密码，如果不一致则返回登录失败结果
        if (!user.getPassword().equals(u.getPassword())) {
            return R.error("密码错误");
        }
        //查看用户状态，如果已为禁用状态，则返回用户账号已禁用结果
        if (u.getStatus() == 0) {
            return R.error("账号已禁用");
        }
        //登录成功，将用户id存入Session并返回登录结果
        request.getSession().setAttribute("user", u.getId());
        return R.success(u).msg("登录成功");
    }

    /**
     * 退出登录
     *
     * @return
     */
    @ApiOperation(value = "退出登录", notes = "需要在localStorage中消除用户信息")
    @GetMapping("/logout")
    public R<String> logout() {
        userService.logout();
        return R.success("退出成功");
    }

    /**
     * 用户注册账户
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "必要:username,password,name,phone,sex")
    public R<String> save(@RequestBody User user) {
        userService.register(user);
        return R.success("注册成功");
    }

    /**
     * 用户列表
     *
     * @param page
     * @param pageSize
     * @param username
     * @return
     */
//    @PreAuthorize("hasAuthority('system:manage:users')")
    @ApiOperation(value = "用户列表", notes = "管理员使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页多少", required = true),
            @ApiImplicitParam(name = "username", value = "用户名"),
    })
    @GetMapping("/page")
    public R<Page<User>> page(Integer page, Integer pageSize, String username, Integer status) {
        //分页构造器
        Page<User> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //姓名模糊搜索
        queryWrapper.like(StringUtils.isNotBlank(username), User::getUsername, username);
        //根据状态筛选
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), User::getStatus, status);
        //排序条件,按照更新时间降序排序
        queryWrapper.orderByDesc(User::getUpdateTime);
        //执行查询
        userService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 用户修改信息
     *
     * @param user
     * @return
     */
//    @PreAuthorize("hasAuthority('system:all:all')")
    @ApiOperation(value = "用户修改信息", notes = "用户自服务,管理员修改状态")
    @PutMapping
    public R<String> update(@RequestBody User user) {
        log.info(user.toString());
        userService.updateById(user);
        return R.success("信息修改成功");
    }

    /**
     * 管理员修改用户状态
     *
     * @param userId
     * @return
     */
//    @PreAuthorize("hasAuthority('system:manage:users')")
    @GetMapping("/updateStatus/{userId}/{status}")
    public R<String> updateUserStatus(@PathVariable Long userId,@PathVariable Integer status) {
        if (status != 1 && status != 0) {
            throw new CustomException("status传参异常");
        }
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getId, userId);
        lambdaUpdateWrapper.set(User::getStatus, status);
        userService.update(null, lambdaUpdateWrapper);
        return R.success("修改成功");
    }

    /**
     * 根据id搜索用户
     *
     * @param id
     * @return
     */
//    @PreAuthorize("hasAuthority('system:manage:users')")
    @ApiOperation(value = "根据id搜索用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, paramType = "path"),
    })
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (Objects.isNull(user)) {
            return R.error("未查询到该用户");
        }
        return R.success(user);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
//    @PreAuthorize("hasAuthority('system:manage:users')")
    @ApiOperation(value = "根据id删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, paramType = "path"),
    })
    @DeleteMapping("/{id}")
    public R<String> remove(@PathVariable Long id) {
        userService.removeById(id);
        return R.success("删除成功");
    }
}
